Grokking Tree Coding Patterns for Interviews
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Course Overview
Introduction to Tree
Types of Tree
BST Traversal Techniques
BST Operations
Introduction to Level Order Traversal Pattern
Reverse Level Order Traversal (easy)
Solution: Reverse Level Order Traversal
Find Largest Value in Each Tree Row (medium)
Solution: Find Largest Value in Each Tree Row
Maximum Width of Binary Tree (medium)
Solution: Maximum Width of Binary Tree
Maximum Level Sum of a Binary Tree (medium)
Solution: Maximum Level Sum of a Binary Tree
Zigzag Traversal (medium)
Solution: Zigzag Traversal
Even Odd Tree (medium)
Solution: Even Odd Tree
N-ary Tree Level Order Traversal (hard)
Solution: N-ary Tree Level Order Traversal
Introduction to Tree Depth Pattern
Maximum Depth (or Height) of Binary Tree (easy)
Solution: Maximum Depth (or Height) of Binary Tree
Minimum Depth of a Binary Tree (easy)
Solution: Minimum Depth of a Binary Tree
Balanced Binary Tree (easy)
Solution: Balanced Binary Tree
Tree Diameter (easy)
Solution: Tree Diameter
Maximum Depth of N-ary Tree (easy)
Solution: Maximum Depth of N-ary Tree
Find maximum depth of subtree (medium)
Solution: Find maximum depth of subtree
Root to Leaf Path Pattern (medium)
Introduction to Root to Leaf Path Pattern
Binary Tree Paths (easy)
Solution: Binary Tree Paths
Sum of Root To Leaf Binary Numbers (easy)
Solution: Sum of Root To Leaf Binary Numbers
Insufficient Nodes in Root to Leaf Paths (medium)
Solution: Insufficient Nodes in Root to Leaf Paths
Smallest String Starting From Leaf (medium)
Solution: Smallest String Starting From Leaf
Pseudo-Palindromic Paths in a Binary Tree (medium)
Solution: Pseudo-Palindromic Paths in a Binary Tree
All Paths for a Sum (medium)
Solution: All Paths for a Sum
Sum of Path Numbers (medium)
Solution: Sum of Path Numbers
Path With Given Sequence (medium)
Solution: Path With Given Sequence
Count Paths for a Sum (medium)
Solution: Count Paths for a Sum
Leaf Processing Pattern (medium)
Introduction to Leaf Processing Pattern
Sum of Left Leaves (easy)
Solution: Sum of Left Leaves
Leaf-Similar Trees (easy)
Solution: Leaf-Similar Trees
Check if all leaves are at same level (medium)
Solution: Check if all leaves are at same level
Delete Leaves With a Given Value (medium)
Solution: Delete Leaves With a Given Value
Deepest Leaves Sum (medium)
Solution: Deepest Leaves Sum
Tree View Pattern (medium)
Introduction to Tree View Pattern
Right View of a Binary Tree (medium)
Solution: Right View of a Binary Tree
Top View Of the Binary Tree (medium)
Solution: Top View Of the Binary Tree
Bottom View Of the Binary Tree (medium)
Solution: Bottom View Of the Binary Tree
Boundary of Binary Tree (medium)
Solution: Boundary of Binary Tree
Comparison of Two Trees Pattern (medium)
Introduction to Comparison of Two Trees Pattern
Symmetric Tree (easy)
Solution: Symmetric Tree
Mirror Image Trees (medium)
Solution: Mirror Image Trees
Subtree of Another Tree (easy)
Solution: Subtree of Another Tree
Isomorphic Trees (medium)
Solution: Isomorphic Trees
Serialize and Deserialize Tree Pattern (hard)
Introduction to Serialize and Deserialize Tree Pattern
Serialize and Deserialize BST (medium)
Solution: Serialize and Deserialize BST
Verify Preorder Serialization of a Binary Tree (medium)
Solution: Verify Preorder Serialization of a Binary Tree
Create Binary Tree From Descriptions (medium)
Solution: Create Binary Tree From Descriptions
Serialize and Deserialize N-ary Tree (hard)
Solution: Serialize and Deserialize N-ary Tree
Solution: Serialize and Deserialize N-ary Tree

Problem Statement

Serialization is the process of converting a data structure or an object into a sequence of bits. This conversion allows the data to be stored in a file, transferred over a network, or saved in memory, with the ability to reconstruct the data later.

Design an algorithm to serialize and deserialize an N-ary tree.

An N-ary tree is a rooted tree where each node can have up to N children. The serialize() method should transform an N-ary tree into a string format and then the deserialize() method should be able to convert this string back to the original tree structure.

There is no restriction on how to perform serialization or deserialization, as long as the process accurately preserves the tree structure.

Examples

Example 1:

  • Input: root = [1,null,2,3,4,null,5,6]
Image
  • Expected Output: [1,null,2,3,4,null,5,6]
  • Explanation: We serialize the deserialize the given N-ary tree.

Example 2:

  • Input: root = [10,null,20,30,null,40,50,60]
Image
  • Expected Output: [10,null,20,30,null,40,50,60]
  • Explanation: We serialize the deserialize the given N-ary tree.

Example 3:

  • Input: root = [100,null,200,300,400,500,null,600,700,null,800]
Image
  • Expected Output: [100,null,200,300,400,500,null,600,700,null,800]

Constraints:

  • The number of nodes in the tree is in the range [0, 104].
  • 0 <= Node.val <= 104
  • The height of the n-ary tree is less than or equal to 1000
  • Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.

Solution

To solve this problem, we need a method to convert an N-ary tree into a string that reflects its structure and a reverse method to rebuild the original tree from this string. For serialization, a level order traversal method can be effective. We traverse the tree level by level, appending each node's value to a result string, and use a separator like null to indicate the end of each level. This approach ensures that each node's children are placed correctly in the resulting string.

For deserialization, the reverse process is applied. We use a queue to keep track of the nodes and build the tree level by level based on the values read from the string. This approach maintains the original structure and can handle trees with different branching factors. It is effective because it allows us to process each node once, ensuring optimal performance.

Step-by-Step Algorithm

  1. Initialize the Serialization Process:

    • Check if the root is null.
      • If root is null, return an empty string "" because there is nothing to serialize.
    • If root is not null, proceed to the next steps.
    • Create an empty StringBuilder object sb to construct the serialized string efficiently.
    • Create a queue (Queue<Node> queue) to perform a level-order traversal starting with the root node.
      • Add the root node to the queue using queue.offer(root).
  2. Level Order Traversal for Serialization:

    • Use a while loop to traverse through the nodes as long as the queue is not empty (while (!queue.isEmpty())):
      • Dequeue a node from the front of the queue using Node node = queue.poll().
      • Check if the dequeued node is null:
        • If the node is null, it indicates the end of a level in the tree.
          • Append "null," to sb to mark the end of the level in the serialized string.
          • Use continue to skip the rest of the loop and start the next iteration.
      • If the dequeued node is not null:
        • Append the node's value (node.val) to sb followed by a comma "," to separate values.
        • Enqueue all children of the current node:
          • Iterate over the node's children (for (Node child : node.children)):
            • Use queue.offer(child) to add each child node to the queue for further processing.
        • Mark the end of the current level:
          • Enqueue a null value (queue.offer(null)) to indicate the end of the level in the tree.
  3. Finalize the Serialization:

    • Once the queue is empty, all nodes have been processed, and the entire tree is serialized.
    • Convert the StringBuilder object sb to a string and return it.
  4. Initialize the Deserialization Process:

    • Check if the input data is empty:
      • If data is empty, return null since there is no tree to deserialize.
    • Split the input string data into an array of strings (String[] nodes) using a comma "," as the delimiter. This gives a list of node values in the order they were serialized.
    • Create a new Node object root with the value parsed from nodes[0] (the first element in the list) and an empty list of children (new ArrayList<>()).
    • Create a queue (Queue<Node> queue) to help in reconstructing the tree level-by-level:
      • Add the root node to the queue using queue.offer(root).
  5. Reconstruct the Tree Level-by-Level:

    • Use a for loop to iterate over the nodes array starting from index 1:
      • Get the Next Parent Node:
        • Dequeue a parent node from the queue using Node parent = queue.poll().
      • Process All Children for the Current Parent Node:
        • Use a while loop to add all children of the parent node until a "null" value is encountered:
          • Check if nodes[i] is "null":
            • If not, create a new Node object child with the value parsed from nodes[i] and an empty list of children.
            • Add the child node to the parent node's list of children (parent.children.add(child)).
            • Enqueue the child node to the queue for processing its children in the future (queue.offer(child)).
            • Increment i to move to the next node value.
        • When "null" is found:
          • End processing for the current parent node and move to the next node in the queue.
  6. Return the Reconstructed Tree:

    • Once the entire nodes array has been processed, the original tree structure is reconstructed.
    • Return the root node, which now represents the deserialized N-ary tree.

Algorithm Walkthrough

Input: [1,null,2,3,4,null,5,6]

  • Step 1: Initialize the process.

    • Check if the root is null:
      • If root is null, return an empty string "" because there is nothing to serialize.
      • In our case, root is not null, so proceed.
    • Initialize tools for serialization:
      • Create a StringBuilder sb to build the output string efficiently.
      • Create a queue (queue) to traverse the tree level by level and add the root node to it:
        queue = [1].
  • Step 2: Start level-order traversal using the queue.

    • Iteration 1:

      • Dequeue node 1:
        queue = [].
        Append the value 1 to sb:
        sb = "1,".
      • Enqueue children of node 1 (2, 3, 4):
        queue = [2, 3, 4].
      • Mark the end of the level with null:
        queue = [2, 3, 4, null].
    • Iteration 2:

      • Dequeue node 2:
        queue = [3, 4, null].
        Append the value 2 to sb:
        sb = "1,2,".
      • Enqueue children of node 2 (5, 6):
        queue = [3, 4, null, 5, 6].
    • Mark the end of the level with null:
      queue = [3, 4, null, 5, 6, null].

    • Iteration 3:

      • Dequeue node 3:
        queue = [4, null, 5, 6, null].
        Append the value 3 to sb:
        sb = "1,2,3,".
      • Node 3 has no children:
      • Mark the end of the level with null:
        queue = [4, null, 5, 6, null, null].
    • Iteration 4:

      • Dequeue node 4:
        queue = [null, 5, 6, null, null].
        Append the value 4 to sb:
        sb = "1,2,3,4,".
      • Node 4 has no children:
      • Mark the end of the level with null:
        queue = [null, 5, 6, null, null, null].
    • Iteration 5:

      • Dequeue null:
        queue = [5, 6, null, null, null].
        Append "null," to sb to indicate the end of the level:
        sb = "1,2,3,4,null,".
    • Iteration 6:

      • Dequeue node 5:
        queue = [6, null, null, null].
        Append the value 5 to sb:
        sb = "1,2,3,4,null,5,".
      • Node 5 has no children:
      • Mark the end of the level with null:
        queue = [6, null, null, null, null].
    • Iteration 7:

      • Dequeue node 6:
        queue = [null, null, null, null].
        Append the value 6 to sb:
        sb = "1,2,3,4,null,5,6,".
      • Node 6 has no children:
      • Mark the end of the level with null:
        queue = [null, null, null, null, null].
    • Iteration 8, 9, 10, 11, 12:

      • Dequeue all null:
        queue = [].
        Append total 5 "null," to sb to indicate the end of the level:
        sb = "1,2,3,4,null,5,6,null,null,null,null,null,"`.

2. Deserialization Process

We will rebuild the tree from the serialized string "1,2,3,4,null,5,6,null,null,null,null,null,".

  • Step 1: Initialize deserialization.

    • Check if the input data is empty:
      • If data is empty, return null since there is no tree to deserialize.
      • In our case, data is not empty, so proceed.
    • Split the input string data into nodes:
      nodes = ["1", "2", "3", "4", "null", "5", "6", "null", "null", "null", "null", "null"].
    • Create the root node from nodes[0]:
      Node root = new Node(1, new ArrayList<>()).
    • Initialize a queue to help build the tree level by level:
      queue = [1].
  • Step 2: Reconstruct the tree using the queue.

    • Iteration 1:

      • Dequeue parent node 1:
        queue = [].
      • Process children of node 1:
        • Check nodes[1] (2):
          • It is not "null", so create Node(2) and add to 1's children:
            root.children = [2].
          • Enqueue Node(2) to the queue:
            queue = [2].
        • Check nodes[2] (3):
          • It is not "null", so create Node(3) and add to 1's children:
            root.children = [2, 3].
          • Enqueue Node(3) to the queue:
            queue = [2, 3].
        • Check nodes[3] (4):
          • It is not "null", so create Node(4) and add to 1's children:
            root.children = [2, 3, 4].
          • Enqueue Node(4) to the queue:
            queue = [2, 3, 4].
        • Check nodes[4] (null):
          • It is "null", marking the end of children for node 1.
    • Iteration 2:

      • Dequeue parent node 2:
        queue = [3, 4].
      • Process children of node 2:
        • Check nodes[5] (5):
          • It is not "null", so create Node(5) and add to 2's children:
            node 2.children = [5].
          • Enqueue Node(5) to the queue:
            queue = [3, 4, 5].
        • Check nodes[6] (6):
          • It is not "null", so create Node(6) and add to 2's children:
            node 2.children = [5, 6].
          • Enqueue Node(6) to the queue:
            queue = [3, 4, 5, 6].
        • Check nodes[7] (null):
          • It is "null", marking the end of children for node 2.
    • Iteration 3:

      • Dequeue parent node 3:
        queue = [4, 5, 6].
      • Process children of node 3:
        • Check nodes[8] (null):
          • It is "null", so 3 has no children.
    • Iteration 4:

      • Dequeue parent node 4:
        queue = [5, 6].
      • Process children of node 4:
        • Check nodes[9] (null):
          • It is "null", so 4 has no children.
    • Iteration 5:

      • Dequeue nodes 5 and 6:
        queue = [].
      • Process children of nodes 5 and 6:
        • Both nodes have no children, so continue.
  • Result:
    The original tree structure is reconstructed correctly.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

The time complexity for both serialization and deserialization is , where N is the number of nodes in the tree. This is because each node is visited once during serialization and deserialization.

Space Complexity

The space complexity is as well, mainly due to the additional storage needed for the queue during the traversal.

Serialize and Deserialize N-ary Tree (hard)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity